package com.example.xcsubsystem.config;

import com.example.xcsubsystem.util.RemoteHeader;
import com.example.xcsubsystem.util.SM4CBCUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Base64;

/**
 * 2024/10/1
 * 拦截器，检查子系统接口调用时http header传递的内容是否正确
 * @author fengyu
 */
@Component
public class AuthInfoInterceptor implements HandlerInterceptor {
// todo 没找到这个配置的值
    @Value("${remote.appKey}")
    private String appKey = "UHSUEHF234SDH2FW";
    @Value("${remote.appSecret}")
    private String appSecret = "uUpaWDuwZRXHVMJrVOcxyw==";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        final Logger log = LoggerFactory.getLogger(AuthInfoInterceptor.class);

        String remote_key =  request.getHeader(RemoteHeader.APPKEY);
        if (null == remote_key) {
            log.info("http headers 中未发现 {}，终止请求", RemoteHeader.APPKEY);
            return false;
        }
        if (!remote_key.equals(appKey)) {
            log.info("统一平台传递的appKey不是本系统的,controller调用结束");
            return false;
        }

        String remote_secret = request.getHeader(RemoteHeader.APPSECRET);
        String remote_iv = request.getHeader("IV");
        byte[] ivBytes = Base64.getDecoder().decode(remote_iv);
        String o_secret;
        try {
            o_secret = SM4CBCUtils.decryptBySM4(appSecret, ivBytes, remote_secret);
            if (o_secret.equals(appSecret)) {
                log.info("接口验证通过");
                return true;
            } else {
                log.info("本系统的appSecret={}, 统一平台传递的Secret{}，不一致，结束controller调用", appSecret, o_secret);
                return false;
            }
        } catch (Exception e){
            log.info("秘钥错误：{}, 终止请求。",e.getMessage());
            return false;
        }
    }
}
